<?php
// +----------------------------------------------------------------------
// | SentCMS [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.tensent.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: molong <molong@tensent.cn> <http://www.tensent.cn>
// +----------------------------------------------------------------------

namespace app\model;

use think\Model;

/**
 * @title 接口管理
 * @description 接口管理
 * @group 用户
 * @header authorization:接口授权
 */
class Interfaces extends Model {

	protected $filter_method = ['__construct'];

	public function getList($param){
		$map = [];
		if (isset($param['name']) && $param['name']) {
			$map[] = array("name", "like", "%".$param['name']."%");
		}
		if (isset($param['path']) && $param['path']) {
			$map[] = array("path", "like", "%".$param['path']."%");
		}
		if (isset($param['method']) && $param['method']) {
			$map[] = array("method", "like", "%".$param['method']."%");
		}
		$list = $this->where($map)->order('id desc')->paginate($param['pageSize']);
		return $list;
	}

	public function refreshData(){
		$list = [];
		$app_path = app()->getAppPath();
		$classname = $this->scanFile($app_path . 'controller/api/');
		foreach ($classname as $value) {
			$class = "\\app\\controller\\api\\" . $value;
			if(class_exists($class)){
				$reflection = new \ReflectionClass($class);
				$group_doc = $this->Parser($reflection->getDocComment());
				$method = $reflection->getMethods(\ReflectionMethod::IS_PUBLIC);
				foreach ($method as $key => $v) {
					if (!in_array($v->name, $this->filter_method)) {
						$title_doc = $this->Parser($v->getDocComment());
						if (isset($title_doc['title']) && $title_doc['title']) {
							$data = array(
								'path' => isset($title_doc['url']) ? trim($title_doc['url']) : 'api/' . strtolower($value) . '/' . strtolower($v->name),
								'name' => trim($title_doc['title']),
								'method' => strtolower($v->name),
								'description' => isset($title_doc['description']) ? $title_doc['description'] : ''
							);
							$id = $this->where('path', $data['path'])->value('id');
							if ($id) {
								$data['id'] = $id;
							}
							$save[] = $data;
						}
					}
				}
			}
		}
		$this->saveAll($save);
	}

	protected function scanFile($path){
		$result = array();
		$files = scandir($path);
		foreach ($files as $file) {
			if ($file != '.' && $file != '..') {
				if (is_dir($path . '/' . $file)) {
					$this->scanFile($path . '/' . $file);
				} else {
					$result[] = substr(basename($file), 0 , -4);
				}
			}
		}
		return $result;
	}

	protected function Parser($text){
		$doc = new \doc\Doc();
		return $doc->parse($text);
	}
}